<?php


namespace Modules\Admin\Http\Controllers\Admin;


use App\Helpers\QueryBuilder;
use App\Http\Controllers\Admin\ApiController;
use App\Http\Resources\BaseResource;
use Modules\Admin\Entities\Role;
use Modules\Admin\Http\Requests\RoleRequest;
use Modules\Admin\Services\RoleService;

class RoleController extends ApiController
{

    public function index()
    {
        $items = QueryBuilder::for(Role::query()->with(['permissions' => function ($query) {
            // 没有下级的权限才是真正对应路由的权限 有下级的通常为菜单
            $query->whereRaw('_rgt - _lft = ?', [1]);
        }]))
            ->filters([
                'guard_name', 'name'
            ])
            ->fields()
            ->includes()
            ->sorts()
            ->page();

        if (!$this->admin->super_admin) {
            $except = [];
            foreach ($items as $key => $value) {
                if (!$this->admin->hasRole($value->name, 'admin')) {
                    $except[] = $value->id;
                }
            }
            // 移除不属于自己的角色
            $items = $items->except($except);
        }

        return $this->success(BaseResource::collection($items));
    }

    public function show(Role $role)
    {
        $role->load('permissions');
        return $this->success($role);
    }

    public function update(Role $role, RoleRequest $request)
    {
        $role = RoleService::getInstance()->Update($role, $request->toArray());
        return $this->success($role);
    }

    public function store(RoleRequest $request)
    {
        $role = RoleService::getInstance()->Add($request->toArray());
        return $this->create($role);
    }

    public function destroy(Role $role)
    {
        RoleService::getInstance()->Destroy($role);
        return $this->noContent();
    }
}
